package cn.bj.ykct;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.apache.commons.fileupload.FileItem;
//import org.apache.commons.fileupload.disk.DiskFileItemFactory;
//import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/view/upload.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/plain;charset=utf-8");
		PrintWriter writer = response.getWriter();
		int count = 0;
		String temppath = "C:/upload";
		try {
			File tempFile = new File(temppath);
			if (!tempFile.exists()) {
				tempFile.mkdirs();
			}
			/*
			DiskFileItemFactory diskFactory = new DiskFileItemFactory();
			diskFactory.setSizeThreshold(4 * 1024);
			diskFactory.setRepository(tempFile);
			ServletFileUpload upload = new ServletFileUpload(diskFactory);
			upload.setSizeMax(4 * 1024 * 1024);
			List<FileItem> fileItems = upload.parseRequest(request);
			Iterator<FileItem> iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					writer.println(item.getFieldName() + " : " + item.getString());
				} else {
					String filename = item.getName();
					filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length());
					File uploadFile = new File(temppath + "/" + filename);
					item.write(uploadFile);
					writer.println("Get file:" + filename);
					writer.println(" filetype: " + item.getContentType());
					count++;
				}
			}
			*/
		} catch (Exception e) {
			e.printStackTrace();
		}
		writer.println("Total file: " + count);
		writer.println("Finished uploading files!");
		writer.close();
	}
}